from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy import desc, and_
from datetime import datetime
import json

from backend.infrastructure.database import db
from backend.models.social_share import SocialShare, SocialShareLike, SocialShareComment, UserFollow, ContentReport
from backend.models.user import User
from backend.services.unified_log_service import UnifiedLogService
from . import miniprogram_bp

log_service = UnifiedLogService()


@miniprogram_bp.route('/social/create-share', methods=['POST'])
@jwt_required()
def create_share():
    """创建分享"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        current_app.logger.info(f'创建分享请求 - 用户ID: {current_user_id}')
        current_app.logger.info(f'创建分享请求 - 数据: {data}')
        
        # 验证必填字段
        if not all(data.get(field) for field in ['title', 'content', 'share_type']):
            missing_fields = [field for field in ['title', 'content', 'share_type'] if not data.get(field)]
            current_app.logger.error(f'缺少必填字段: {missing_fields}')
            return jsonify({'success': False, 'message': f'缺少必填字段: {missing_fields}'}), 400
        
        # 验证分享类型
        valid_types = ['intervention', 'experience', 'question', 'achievement']
        if data['share_type'] not in valid_types:
            current_app.logger.error(f'无效的分享类型: {data["share_type"]}, 有效类型: {valid_types}')
            return jsonify({'success': False, 'message': '无效的分享类型'}), 400
        
        current_app.logger.info(f'分享类型验证通过: {data["share_type"]}')
        
        # 获取用户信息
        user = User.query.get(current_user_id)
        if not user:
            current_app.logger.error(f'用户不存在: {current_user_id}')
            return jsonify({'success': False, 'message': '用户不存在'}), 404
            
        current_app.logger.info(f'用户信息获取成功: {user.id}')
        
        # 处理图片：只接受 /media/ 开头的相对路径，过滤其它格式
        raw_images = data.get('images') or []
        if not isinstance(raw_images, list):
            return jsonify({'success': False, 'message': 'images 必须为数组'}), 400
        cleaned_images = []
        for img in raw_images:
            if not img or not isinstance(img, str):
                continue
            val = img.strip()
            # 已是完整 http(s) 说明前端传错，拒绝
            if val.lower().startswith('http://') or val.lower().startswith('https://'):
                current_app.logger.warning(f'create_share 拒绝绝对URL: {val}')
                return jsonify({'success': False, 'message': '图片URL必须为后端返回的相对路径'}), 400
            # 允许带多余的 /api/miniprogram/ 前缀，剥离
            if val.startswith('/api/miniprogram/'):
                val = '/' + val[len('/api/miniprogram/'):].lstrip('/')
            if not val.startswith('/'):
                val = '/' + val
            if not val.startswith('/media/'):
                current_app.logger.warning(f'create_share 跳过非媒体路径: {val}')
                continue
            cleaned_images.append(val)
        # 去重保持顺序
        seen = set()
        deduped_images = []
        for v in cleaned_images:
            if v not in seen:
                seen.add(v)
                deduped_images.append(v)

        # 创建分享记录（images 以 JSON 保存）
        share = SocialShare(
            user_id=current_user_id,
            student_id=user.student_id,
            title=data['title'],
            content=data['content'],
            images=json.dumps(deduped_images) if deduped_images else None,
            share_type=data['share_type'],
            tags=data.get('tags', ''),
            status='active'  # 直接设为active，不需要审核
        )
        
        current_app.logger.info(f'分享对象创建成功: {share.title}')
        
        db.session.add(share)
        db.session.commit()
        
        current_app.logger.info(f'分享保存成功: ID={share.id}')
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='CREATE',
            table_name='social_shares',
            record_id=share.id,
            details=f'创建分享: {share.title}'
        )
        
        return jsonify({
            'success': True,
            'message': '分享创建成功',
            'data': {
                'id': share.id,
                'title': share.title,
                'content': share.content,
                'share_type': share.share_type,
                'created_at': share.created_at.isoformat() if share.created_at else datetime.now().isoformat()
            }
        }), 201  # 返回201状态码表示创建成功
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'创建分享失败: {str(e)}', exc_info=True)
        return jsonify({'success': False, 'message': '创建分享失败'}), 500


@miniprogram_bp.route('/social/get-share-detail', methods=['GET'])
@jwt_required()  
def get_share_detail():
    """获取分享详情"""
    try:
        current_user_id = get_jwt_identity()
        share_id = request.args.get('share_id', type=int)
        
        if not share_id:
            return jsonify({'success': False, 'message': '缺少分享ID'}), 400
            
        current_app.logger.info(f'获取分享详情请求 - 用户ID: {current_user_id}, 分享ID: {share_id}')
        
        # 查询分享详情
        share = db.session.query(SocialShare).filter_by(id=share_id).first()
        
        if not share:
            return jsonify({'success': False, 'message': '分享不存在'}), 404
            
        # 获取作者信息
        author = db.session.query(User).filter_by(id=share.user_id).first()
        
        # 查询当前用户是否点赞了这个分享
        is_liked = False
        if current_user_id:
            like_record = db.session.query(SocialShareLike).filter_by(
                share_id=share_id, 
                user_id=current_user_id
            ).first()
            is_liked = like_record is not None
        
        # 查询当前用户是否关注了作者
        is_following = False
        if current_user_id and current_user_id != share.user_id:
            follow_record = db.session.query(UserFollow).filter_by(
                follower_id=current_user_id,
                following_id=share.user_id
            ).first()
            is_following = follow_record is not None
        
        # 处理图片URL - 转换为相对路径
        image_urls = []
        if share.images:
            try:
                images = json.loads(share.images)
                for img_url in images:
                    if not img_url:
                        continue
                    if isinstance(img_url, str):
                        v = img_url.strip()
                        if v.startswith('http://localhost:5000'):
                            v = v.replace('http://localhost:5000', '')
                        # 只保留 /media/ 相对路径或已是 http(s) 完整URL（历史兼容）
                        if v.startswith('/media/') or v.startswith('http://') or v.startswith('https://'):
                            image_urls.append(v)
            except Exception as e:
                current_app.logger.warning(f'解析分享图片失败 share_id={share.id}: {e}')
                image_urls = []
        
        # 构建返回数据
        share_data = {
            'id': share.id,
            'title': share.title,
            'content': share.content,
            'username': author.username if author else '未知用户',
            'user_id': share.user_id,
            'avatar_url': author.avatar if author and author.avatar else '/static/images/default-avatar.png',
            'created_at': share.created_at.isoformat(),
            'like_count': share.like_count,
            'comment_count': share.comment_count,
            'share_count': share.share_count,
            'is_liked': is_liked,
            'is_following': is_following,
            'image_urls': image_urls,
            'tags': share.tags.split(',') if share.tags else [],
            'share_type': share.share_type
        }
        
        current_app.logger.info(f'分享详情获取成功: {share_data}')
        
        # 获取评论列表
        comments = db.session.query(
            SocialShareComment.id,
            SocialShareComment.content,
            SocialShareComment.created_at,
            User.username,
            User.avatar
        ).join(
            User, SocialShareComment.user_id == User.id
        ).filter(
            and_(
                SocialShareComment.share_id == share_id,
                SocialShareComment.parent_id.is_(None)  # 只获取主评论
            )
        ).order_by(SocialShareComment.created_at.asc()).all()
        
        comments_data = []
        for comment in comments:
            comment_data = {
                'id': comment.id,
                'content': comment.content,
                'created_at': comment.created_at.isoformat(),
                'username': comment.username,
                'avatar_url': comment.avatar if comment.avatar else '/static/images/default-avatar.png'
            }
            comments_data.append(comment_data)
        
        return jsonify({
            'success': True,
            'data': {
                'share': share_data,
                'comments': comments_data
            }
        })
        
    except Exception as e:
        current_app.logger.error(f'获取分享详情失败: {str(e)}', exc_info=True)
        return jsonify({'success': False, 'message': '获取分享详情失败'}), 500


@miniprogram_bp.route('/social/get-comments', methods=['GET'])
@jwt_required()
def get_comments():
    """获取分享的评论列表"""
    try:
        current_user_id = get_jwt_identity()
        share_id = request.args.get('share_id', type=int)
        
        if not share_id:
            return jsonify({'success': False, 'message': '缺少分享ID'}), 400
        
        # 查询主评论（parent_id为None的评论）
        main_comments = db.session.query(
            SocialShareComment.id,
            SocialShareComment.content,
            SocialShareComment.created_at,
            User.username,
            User.avatar.label('avatar_url')
        ).join(
            User, SocialShareComment.user_id == User.id
        ).filter(
            and_(
                SocialShareComment.share_id == share_id,
                SocialShareComment.parent_id.is_(None)
            )
        ).order_by(SocialShareComment.created_at.asc()).all()
        
        comments_data = []
        for comment in main_comments:
            # 查询这个评论的回复
            replies = db.session.query(
                SocialShareComment.id,
                SocialShareComment.content,
                SocialShareComment.created_at,
                User.username,
                User.avatar.label('avatar_url')
            ).join(
                User, SocialShareComment.user_id == User.id
            ).filter(
                SocialShareComment.parent_id == comment.id
            ).order_by(SocialShareComment.created_at.asc()).all()
            
            replies_data = [{
                'id': reply.id,
                'content': reply.content,
                'created_at': reply.created_at.isoformat(),
                'username': reply.username,
                'avatar_url': reply.avatar_url
            } for reply in replies]
            
            comment_data = {
                'id': comment.id,
                'content': comment.content,
                'created_at': comment.created_at.isoformat(),
                'username': comment.username,
                'avatar_url': comment.avatar_url,
                'replies': replies_data
            }
            comments_data.append(comment_data)
        
        return jsonify({'success': True, 'data': comments_data}), 200
        
    except Exception as e:
        log_service.log_error('get_comments', f'获取评论列表失败: {str(e)}')
        current_app.logger.error(f'获取评论列表失败: {str(e)}')
        return jsonify({'success': False, 'message': '获取评论列表失败'}), 500


@miniprogram_bp.route('/social/get-shares', methods=['GET'])
def get_shares():
    """获取分享列表"""
    try:
        # 获取当前用户ID，如果未登录则为None
        current_user_id = None
        try:
            current_user_id = get_jwt_identity()
        except:
            pass  # 用户未登录，继续处理
        
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        share_type = request.args.get('share_type')
        user_id = request.args.get('user_id', type=int)
        
        # 构建查询条件
        query = SocialShare.query.filter(SocialShare.status == 'active')
        
        if share_type:
            query = query.filter(SocialShare.share_type == share_type)
        if user_id:
            query = query.filter(SocialShare.user_id == user_id)
        
        # 分页查询
        pagination = query.order_by(desc(SocialShare.created_at)).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        shares = pagination.items
        
        # 检查当前用户是否已点赞（仅在用户登录时检查）
        shares_data = []
        for share in shares:
            share_dict = share.to_dict()
            # 统一 image_urls 数组
            images_array = share_dict.get('images') or []
            normalized_images = []
            for u in images_array:
                if not u or not isinstance(u, str):
                    continue
                v = u.strip()
                if v.startswith('http://localhost:5000'):
                    v = v.replace('http://localhost:5000', '')
                # 只接受 /media/ 相对或 http(s)（历史容错）
                if v.startswith('/media/') or v.startswith('http://') or v.startswith('https://'):
                    normalized_images.append(v)
            share_dict['image_urls'] = normalized_images
            # 头像统一为 avatar_url
            if share_dict.get('user_info'):
                ui = share_dict['user_info']
                ui['avatar_url'] = ui.get('avatar_url') or ui.get('avatar')
            if current_user_id:
                like = SocialShareLike.query.filter(
                    and_(SocialShareLike.share_id == share.id, SocialShareLike.user_id == current_user_id)
                ).first()
                share_dict['is_liked'] = like is not None
            else:
                share_dict['is_liked'] = False
            shares_data.append(share_dict)
        
        return jsonify({
            'success': True,
            'data': {
                'shares': shares_data,
                'pagination': {
                    'page': page,
                    'per_page': per_page,
                    'total': pagination.total,
                    'pages': pagination.pages,
                    'has_next': pagination.has_next,
                    'has_prev': pagination.has_prev
                }
            }
        })
        
    except Exception as e:
        current_app.logger.error(f'获取分享列表失败: {str(e)}')
        return jsonify({'success': False, 'message': '获取分享列表失败'}), 500


@miniprogram_bp.route('/social/toggle-like', methods=['POST'])
@jwt_required()
def toggle_like():
    """点赞/取消点赞"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        share_id = data.get('share_id')
        
        if not share_id:
            return jsonify({'success': False, 'message': '缺少分享ID'}), 400
        
        share = SocialShare.query.get(share_id)
        if not share:
            return jsonify({'success': False, 'message': '分享不存在'}), 404
        
        # 检查是否已点赞
        existing_like = SocialShareLike.query.filter(
            and_(SocialShareLike.share_id == share_id, SocialShareLike.user_id == current_user_id)
        ).first()
        
        if existing_like:
            # 取消点赞
            db.session.delete(existing_like)
            share.like_count = max(0, share.like_count - 1)
            action = '取消点赞'
            is_liked = False
        else:
            # 添加点赞
            like = SocialShareLike(share_id=share_id, user_id=current_user_id)
            db.session.add(like)
            share.like_count += 1
            action = '点赞'
            is_liked = True
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='UPDATE',
            table_name='social_shares',
            record_id=share_id,
            details=f'{action}: {share.title}'
        )
        
        return jsonify({
            'success': True,
            'message': f'{action}成功',
            'data': {'is_liked': is_liked, 'like_count': share.like_count}
        })
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'点赞操作失败: {str(e)}')
        return jsonify({'success': False, 'message': '点赞操作失败'}), 500


@miniprogram_bp.route('/social/create-comment', methods=['POST'])
@jwt_required()
def create_comment():
    """创建评论"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        if not data.get('content'):
            return jsonify({'success': False, 'message': '评论内容不能为空'}), 400
        
        share_id = data.get('share_id')
        if not share_id:
            return jsonify({'success': False, 'message': '缺少分享ID'}), 400
        
        share = SocialShare.query.get(share_id)
        if not share:
            return jsonify({'success': False, 'message': '分享不存在'}), 404
        
        # 创建评论
        comment = SocialShareComment(
            share_id=share_id,
            user_id=current_user_id,
            parent_id=data.get('parent_id'),
            content=data['content']
        )
        
        db.session.add(comment)
        share.comment_count += 1
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='CREATE',
            table_name='social_share_comments',
            record_id=comment.id,
            details=f'评论分享: {share.title}'
        )
        
        return jsonify({
            'success': True,
            'message': '评论成功',
            'data': comment.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'创建评论失败: {str(e)}')
        return jsonify({'success': False, 'message': '创建评论失败'}), 500


@miniprogram_bp.route('/social/toggle-follow', methods=['POST'])
@jwt_required()
def toggle_follow():
    """关注/取消关注用户"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        if not data.get('following_id'):
            return jsonify({'success': False, 'message': '缺少被关注用户ID'}), 400
        
        following_id = data['following_id']
        
        # 不能关注自己
        if current_user_id == following_id:
            return jsonify({'success': False, 'message': '不能关注自己'}), 400
        
        # 检查被关注用户是否存在
        following_user = User.query.get(following_id)
        if not following_user:
            return jsonify({'success': False, 'message': '被关注用户不存在'}), 404
        
        # 检查是否已关注
        existing_follow = UserFollow.query.filter(
            and_(UserFollow.follower_id == current_user_id, UserFollow.following_id == following_id)
        ).first()
        
        if existing_follow:
            # 取消关注
            db.session.delete(existing_follow)
            action = '取消关注'
            is_following = False
        else:
            # 添加关注
            follow = UserFollow(follower_id=current_user_id, following_id=following_id)
            db.session.add(follow)
            action = '关注'
            is_following = True
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='UPDATE',
            table_name='user_follows',
            record_id=following_id,
            details=f'{action}用户: {following_user.username}'
        )
        
        return jsonify({
            'success': True,
            'message': f'{action}成功',
            'data': {'is_following': is_following}
        })
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'关注操作失败: {str(e)}')
        return jsonify({'success': False, 'message': '关注操作失败'}), 500


@miniprogram_bp.route('/social/record-share', methods=['POST'])
@jwt_required()
def record_share():
    """记录分享事件"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        share_id = data.get('share_id')
        if not share_id:
            return jsonify({'success': False, 'message': '缺少分享ID'}), 400
        
        share = SocialShare.query.get(share_id)
        if not share:
            return jsonify({'success': False, 'message': '分享不存在'}), 404
        
        # 增加分享计数
        share.share_count = (share.share_count or 0) + 1
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='SHARE',
            table_name='social_shares',
            record_id=share_id,
            details=f'分享内容: {share.title}'
        )
        
        return jsonify({
            'success': True,
            'message': '分享记录成功',
            'data': {'share_count': share.share_count}
        })
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'记录分享失败: {str(e)}')
        return jsonify({'success': False, 'message': '记录分享失败'}), 500


@miniprogram_bp.route('/social/add-comment', methods=['POST'])
@jwt_required()
def add_comment():
    """添加评论"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['share_id', 'content']
        missing_fields = [field for field in required_fields if not data.get(field)]
        if missing_fields:
            return jsonify({'success': False, 'message': f'缺少必填字段: {missing_fields}'}), 400
        
        share_id = data.get('share_id')
        content = data.get('content', '').strip()
        parent_id = data.get('parent_id')  # 回复评论时使用
        
        if not content:
            return jsonify({'success': False, 'message': '评论内容不能为空'}), 400
            
        # 验证分享是否存在
        share = db.session.query(SocialShare).filter_by(id=share_id).first()
        if not share:
            return jsonify({'success': False, 'message': '分享不存在'}), 404
            
        # 如果是回复评论，验证父评论是否存在
        if parent_id:
            parent_comment = db.session.query(SocialShareComment).filter_by(id=parent_id).first()
            if not parent_comment:
                return jsonify({'success': False, 'message': '父评论不存在'}), 404
        
        current_app.logger.info(f'用户 {current_user_id} 添加评论到分享 {share_id}: {content}')
        
        # 创建评论
        comment = SocialShareComment(
            share_id=share_id,
            user_id=current_user_id,
            content=content,
            parent_id=parent_id
        )
        
        db.session.add(comment)
        
        # 更新分享的评论数量
        share.comment_count = share.comment_count + 1
        
        db.session.commit()
        
        # 获取用户信息用于返回
        user = db.session.query(User).filter_by(id=current_user_id).first()
        
        current_app.logger.info(f'评论添加成功: ID={comment.id}')
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='CREATE',
            table_name='social_share_comments',
            record_id=comment.id,
            details=f'添加评论到分享{share_id}: {content[:50]}'
        )
        
        return jsonify({
            'success': True,
            'message': '评论成功',
            'data': {
                'comment': {
                    'id': comment.id,
                    'content': comment.content,
                    'created_at': comment.created_at.isoformat(),
                    'username': user.username if user else '未知用户',
                    'avatar_url': user.avatar if user and user.avatar else '/static/images/default-avatar.png',
                    'parent_id': parent_id
                },
                'comment_count': share.comment_count
            }
        })
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'添加评论失败: {str(e)}', exc_info=True)
        return jsonify({'success': False, 'message': '评论失败'}), 500